package org.sample.commons.edoc;

import org.sample.commons.bean.BeanUtils;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;

/**
 * Created by alan on 17/6/9.
 */
public class Column {

    protected String title;
    protected Method[] readMethods;
    protected boolean numeric;
    private Format format;

    public String readValue(Object data) {
        Object value = data;
        for (Method readMethod : readMethods) {
            if (value != null) {
                if (value instanceof Collection)
                    break;
                if (value.getClass().isArray())
                    break;
                value = BeanUtils.getValue(value, readMethod);
            }
        }
        if (value == null)
            return "";
        if (format != null)
            return format.format(value);

        if (value instanceof Collection) {
            int i = readMethods.length - 1;
            StringBuilder sb = new StringBuilder();
            for (Object o : (Collection) value) {
                if (readMethods.length > 1)
                    sb.append(BeanUtils.getValue(o, readMethods[i])).append(",");
                else
                    sb.append(String.valueOf(o)).append(",");

            }
            if (sb.length() > 0)
                sb.deleteCharAt(sb.length() - 1).toString();
            return sb.toString();
        }
        if (value.getClass().isArray()) {
            int i = readMethods.length - 1;
            StringBuilder sb = new StringBuilder();
            for (Object o : (Object[]) value) {
                if (readMethods.length > 1)
                    sb.append(BeanUtils.getValue(o, readMethods[i])).append(",");
                else
                    sb.append(String.valueOf(o)).append(",");
            }
            if (sb.length() > 0)
                sb.deleteCharAt(sb.length() - 1).toString();
            return sb.toString();
        }

        return String.valueOf(value);
    }

    public Column(Method[] readMethods, String title) {
        this.readMethods = readMethods;
        this.title = title;
    }


    public Column(Method[] readMethods, String title, Format format) {
        this(readMethods, title);
        this.format = format;
    }

    public Column(Method[] readMethods, String title, Boolean numeric, Format format) {
        this(readMethods, title, format);
        if (numeric != null)
            this.numeric = numeric;
    }

    @Override
    public String toString() {
        return new StringBuilder(Arrays.toString(readMethods)).append(",").append(title).append(",").append(numeric).toString();
    }
}